package com.ikingtech.platform.service.cluster.controller;

import com.ikingtech.framework.sdk.cluster.client.ClusterClient;
import com.ikingtech.framework.sdk.cluster.node.ClusterNode;
import com.ikingtech.framework.sdk.cluster.node.ClusterNodeManager;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import com.ikingtech.platform.service.cluster.entity.ClusterNodeDO;
import com.ikingtech.platform.service.cluster.model.ClusterNodeDTO;
import com.ikingtech.platform.service.cluster.service.ClusterNodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
@ApiController(value = "/cluster/management", name = "集群管理", description = "集群管理")
public class ClusterController {

    private final ClusterNodeManager nodeManager;

    private final ClusterClient client;

    private final ClusterNodeService nodeService;

    @PostRequest(order = 1,value = "/node/add", summary = "", description = "")
    public R<Object> add(@RequestBody ClusterNodeDTO node) {
        ClusterNodeDO entity = Tools.Bean.copy(node, ClusterNodeDO.class);
        entity.setId(Tools.Id.uuid());
        entity.setAlive(false);
        this.nodeService.save(entity);

        // 添加到本地实例列表中
        ClusterNode clusterNode = Tools.Bean.copy(node, ClusterNode.class);
        this.nodeManager.put(clusterNode);
        // 向原有的其他节点广播有新的节点加入到集群，并让本地客户端和新的实例节点建立连接
        this.client.publishJoinMessage(clusterNode);
        this.client.newConnection(clusterNode);
        return R.ok();
    }
}
